package com.vacation.vacationdemo.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vacation.vacationdemo.dto.VacationDto;
import com.vacation.vacationdemo.entity.Employee;
import com.vacation.vacationdemo.entity.Vacation;
import com.vacation.vacationdemo.mapper.VacationMapper;
import com.vacation.vacationdemo.service.VacationService;
import com.vacation.vacationdemo.util.ThreadLocalUtil;
import com.vacation.vacationdemo.vo.EmployeeVo;
import com.vacation.vacationdemo.vo.VacationVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 杨光
 * @date 2022年03月09日 11:01
 */
@Service
public class VacationServiceImpl implements VacationService {

    @Autowired
    private VacationMapper vacationMapper;



    @Override
    public PageInfo<VacationVo> selectVacation(Integer pageNum, Integer pageSize) {
//        Employee employee = ThreadLocalUtil.EmpThreadLocal.get();

        //获取shiro的session
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        EmployeeVo loginUser = (EmployeeVo)session.getAttribute("loginUser");

        PageHelper.startPage(pageNum,pageSize);
        List<VacationVo> vacationVoList = vacationMapper.selectVacation(loginUser.getEmpId());

        PageInfo<VacationVo> pageInfo = new PageInfo<>(vacationVoList);

        return pageInfo;
    }

    @Override
    public void cancelApply(Integer vacationId) {
        vacationMapper.cancelApply(vacationId);
    }

    @Override
    public Boolean addVacation(VacationDto vacationDto) {


        //1.获取员工id
        Employee employee = ThreadLocalUtil.EmpThreadLocal.get();
        Integer empId = employee.getEmpId();
        //2.获取部门id
        Integer deptId = employee.getDeptId();
        //3.保存文件
        MultipartFile file = vacationDto.getFile();
        String fileName = System.nanoTime()+file.getOriginalFilename();
        try{
            file.transferTo(new File("D:/app/imgs/"+fileName));
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }

        Vacation vacation = new Vacation();
        //复制对象的属性
        BeanUtils.copyProperties(vacationDto,vacation);
        vacation.setEmpId(empId);
        vacation.setDeptId(deptId);
        vacation.setPictureUrl(fileName);
        vacation.setVacationStatusId(1);//等待经理审批
        //4.添加数据到表
        int cnt = vacationMapper.insertVacation(vacation);
        if(cnt!=1){
            return false;
        }

        return true;

    }

    @Override
    public PageInfo<VacationVo> dynamicSearchVacation(Integer pageNum, Integer pageSize,
                                                      Integer deptId, String empName) {

        //获取shiro的session
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        EmployeeVo loginUser = (EmployeeVo)session.getAttribute("loginUser");

        Integer vacationStatusId = null;
//        Employee employee = ThreadLocalUtil.EmpThreadLocal.get();
        if(loginUser.getRoleId()==2){
            vacationStatusId=1;
        }
        if(loginUser.getRoleId()==3){
            vacationStatusId=2;
        }

        PageHelper.startPage(pageNum,pageSize);
        List<VacationVo> list = vacationMapper.dynamicSearchVacation(deptId,empName,vacationStatusId);

        PageInfo<VacationVo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public String exportVacation(Integer deptId, String empName,String downloadFilePath) {

        //获取shiro的session
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        EmployeeVo loginUser = (EmployeeVo)session.getAttribute("loginUser");

        Integer vacationStatusId = null;
//        Employee employee = ThreadLocalUtil.EmpThreadLocal.get();
        if(loginUser.getRoleId()==2){
            vacationStatusId=1;
        }
        if(loginUser.getRoleId()==3){
            vacationStatusId=2;
        }
        List<VacationVo> list = vacationMapper.dynamicSearchVacation(deptId,empName,vacationStatusId);


        String fileName="vacation_"+System.currentTimeMillis()+".csv";

        //生成文件
        File file = new File(downloadFilePath + fileName);
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(file));

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

            for (VacationVo vacationVo : list) {
                StringBuilder line = new StringBuilder();
                line.append(vacationVo.getEmpName()).append(",")
                        .append(vacationVo.getStatusName()).append(",")
                        .append(format.format(vacationVo.getVacationStartTime()));
                bw.write(line.toString());
                bw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(bw!=null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return fileName;
    }

    @Override
    public void doBatchApprove(List<Integer> vacationIds) {

        Integer vacationStatusId = null;
        Employee employee = ThreadLocalUtil.EmpThreadLocal.get();
        if(employee.getRoleId()==2){
            vacationStatusId=2;
        }
        if(employee.getRoleId()==3){
            vacationStatusId=3;
        }

        vacationMapper.doBatchApprove(vacationIds,vacationStatusId);
    }

    @Override
    public void doReject(List<Integer> vacationIds) {
        vacationMapper.doReject(vacationIds);
    }

    @Override
    public void upload(MultipartFile file) {
        BufferedReader br = null;
        List<Vacation> list = new ArrayList();
        try {
            br = new BufferedReader(new InputStreamReader(file.getInputStream()));
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String line=null;

            while((line=br.readLine())!=null){
                String[] fields = line.split(",");
                Vacation vacation = new Vacation();
                vacation.setEmpId(Integer.valueOf(fields[0]));//empId
                vacation.setVacationTypeId(Integer.valueOf(fields[1]));//VacationTypeId
                vacation.setVacationStartTime(format.parse(fields[2]));
                vacation.setVacationEndTime(format.parse(fields[3]));//endTime
                vacation.setRemark(fields[4]);//remark
                vacation.setDeptId(Integer.valueOf(fields[5]));//empId
                vacation.setCellPhone(fields[6]);//cellphone
                vacation.setVacationStatusId(Integer.valueOf(fields[7]));//VacationStatusId
                vacation.setPictureUrl(fields[8]);//picture_url
                list.add(vacation);
            }
            //批量插入记录
            vacationMapper.insertBatch(list);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public static void main(String[] args) {
        BufferedReader br = null;
        File file = new File("C:\\Users\\Administrator\\Desktop\\tb_vacation.csv");
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            String line=null;
            while((line=br.readLine())!=null){
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
